package com.edou.system.service.impl;

import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.edou.system.dao.ISysEmailDao;
import com.edou.system.entity.SysEmail;
import com.edou.system.entity.SysEmailTemplate;
import com.edou.system.service.ISysEmailTemplateService;
import com.edou.system.service.ISysMailService;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 邮件service
 * @creator     admin
 * @create-time 2016年5月9日   下午5:48:03
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Service
public class SysMailServiceImpl implements ISysMailService {

	private Log logger = LogFactory.getLog(SysMailServiceImpl.class);

	@Resource(name = "freeMarkerConfigurer")
	FreeMarkerConfigurer freeMarkerConfigurer;

	@Autowired
	private ISysEmailTemplateService emailTemplateService;
	
	@Autowired
	private ISysEmailDao sysEmailDao;
	
	/**
	 * 单条保存发邮件信息
	 */
	public void sendEmail(String templateId, String emailTitle, String emailSendTo, Map<String, Object> data) throws MessagingException {
		this.batchSendEmail(templateId, emailTitle, new String[]{emailSendTo}, data);
	}

	/**
	 * 
	 * 批量保存发邮件信息
	 * @throws MessagingException 
	 */
	public void batchSendEmail(String templateId, String emailTitle, String[] emailSendTo, Map<String, Object> data) throws MessagingException {
		SysEmailTemplate template = emailTemplateService.getEmailTemplateById(templateId);
		if(null==template){
			logger.error("邮件模板不存在,传入模板ID:" + templateId);
			return;
		}
		
		if(null == emailSendTo){
			logger.error("收件人不能为空");
			throw new MessagingException("收件人不能为空");
		}
		
		//加载模板内容
		StringTemplateLoader stringLoader = new StringTemplateLoader();
		stringLoader.putTemplate(templateId, template.getContent());
		Configuration cfg = freeMarkerConfigurer.getConfiguration();
		cfg.setTemplateLoader(stringLoader);
		try {
			Template markTemplate = cfg.getTemplate(templateId);
			String content = FreeMarkerTemplateUtils.processTemplateIntoString(markTemplate, data);
			SysEmail email = new SysEmail();
			
			email.setCreateBy("system");
			email.setUpdateBy("system");
			email.setEmail(StringUtils.join(emailSendTo, ","));
			email.setContent(content);
			email.setFlag(0);
			email.setTitle(emailTitle);
			email.setType(templateId);
			//保存
			sysEmailDao.add(email);
		} catch (Exception ex) {
			String msg = "新增邮件时发生异常:" + ex.getMessage();
			logger.error(msg,ex);
		}
	}
}
